package cn.zgliang.blog.web;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/3/31 17:49
 * 描述：
 */
@RestController
public class ImageManager {
    @RequestMapping(value = { "/blogimages/{filename}" }, method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable("filename") String fileName) throws IOException {
        System.out.println(fileName);
        String property = System.getProperty("user.dir");
        File file3 = new File(property);
        String[] s = StringUtils.split(fileName,"_");
        fileName = s[0] + "/" + s[1];
        String filePath = file3.getParent() + File.separator + "images" + File.separator + fileName;
        System.out.println(filePath);
        @SuppressWarnings("resource")
        InputStream in = new FileInputStream(new File(filePath));// 将该文件加入到输入流之中
        byte[] body = null;
        body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
        in.read(body);// 读入到输入流里面

        fileName = new String(fileName.getBytes("gbk"), "iso8859-1");// 防止中文乱码
        HttpHeaders headers = new HttpHeaders();// 设置响应头
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
}
